package com.zj.small.controller;

import com.zj.small.pojo.Result;
import com.zj.small.pojo.User;
import com.zj.small.service.SendEmail;
import com.zj.small.service.UserService;
import com.zj.small.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SendEmail sendEmail;
    private String nowCaptcha;
    // 登录
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> payload) {
        String username = payload.get("username");
        String password = payload.get("password");
        if (username == null || username.trim().equals("") || password == null || password.trim().equals("")) {
            return Result.error("用户名或密码不能为空！");
        } else {
            // 查询
            User user = userService.findByUsername(username);
            String pw = Md5Util.StringInMd5(password);
            if(user != null && user.getPassword().equals(pw)){
                return Result.success();
            } else {
                return Result.error("用户名或密码错误");
            }
        }
    }


    // 注册函数
    @PostMapping("/register")
    public Result register(String username, String password) {
        if (username == null || username.trim().equals("") || password == null || password.trim().equals("")){
            return Result.error("用户名或密码不能为空");
        }else {
            // 查询
            User user = userService.findByUsername(username);

            if(user == null){
                userService.register(username,password);
                return Result.success();
            }else{
                return Result.error("用户名已存在");
            }
        }
    }

}
